package com.fjwt.gz.coupon.tlpay;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.SendCouponBo;
import com.shopoint.openapis.ClientConfiguration;
import com.shopoint.openapis.OpenApisClient;
import com.shopoint.openapis.common.auth.CredentialsProvider;
import com.shopoint.openapis.common.auth.DefaultCredentialProvider;
import com.shopoint.openapis.model.CouponSendReqeust;
import com.shopoint.openapis.model.GenericResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * 通联发券
 */
@Slf4j
@Service
public class TlpayCouponSendService {
    //TODO 注意： 上面记得封装一层，统一调用，通过不同通道调用不同的逻辑，
    private static final Logger tlPayLogger = LoggerFactory.getLogger("tlPay");

    public JSONObject couponSend(SendCouponBo sendCouponBo) {
        String logPrefix = "通联支付通道发券】";
        tlPayLogger.info("{}，进来的参数信息是：{}", logPrefix, JSONUtil.toJsonStr(sendCouponBo));

        if (Objects.isNull(sendCouponBo)) {
            throw new BizException("发券参数缺失！");
        }
        String thirdActivityId = sendCouponBo.getStockId();
        String openId = sendCouponBo.getOpenId();
        JSONObject json = sendCouponBo.getAuthConfig();
        String url = json.getString("url");
        String appId = json.getString("appId");
        String publicKey = json.getString("publicKey");
        String privateKey = json.getString("privateKey");
        String aesKey = json.getString("aesKey");
        try {
            tlPayLogger.debug("appId:{},publicKey:{},aesKey:{},privateKey:{}", appId, publicKey, aesKey, privateKey);
            CredentialsProvider openApis = new DefaultCredentialProvider(appId, publicKey, aesKey, privateKey);
            tlPayLogger.debug("url:{},openApis:{}", url, JSONUtil.toJsonStr(openApis));
            OpenApisClient client = new OpenApisClient(url, openApis, new ClientConfiguration());
            String orderId = UUID.randomUUID().toString();
            JSONObject sendJson = new JSONObject();
            sendJson.put("idType", "1");
            sendJson.put("openId", openId);
            sendJson.put("thirdActivityId", thirdActivityId);
            sendJson.put("orderId", orderId);
            tlPayLogger.info("通联发券请求参数：{}", JSONObject.toJSONString(sendJson));
            GenericResult result = client.bankServiceCouponSend(new CouponSendReqeust(1, openId, Integer.parseInt(thirdActivityId), orderId, null));
            tlPayLogger.info("通联发券接口请求返回报文信息：JSON.toJSONString(result) = {}", JSON.toJSONString(result));
            if (!"0".equals(result.getCode())) {
                String msg = result.getMsg();
                String err = "";
                String errStr = "";
                if (StringUtils.isNotEmpty(msg) && msg.contains("RID")) {
                    if (msg.contains("微信领券失败:")) {
                        err = StringUtils.substringAfter(msg, "微信领券失败:");
                        errStr = StringUtils.substringBefore(err, "RID");
                    } else if (msg.contains("领取失败:")) {
                        err = StringUtils.substringAfter(msg, "领取失败:");
                        errStr = StringUtils.substringBefore(err, "RID");
                    }
                }
                tlPayLogger.info("错误信息：{}", StringUtils.isNotEmpty(errStr) ? errStr : "垫资方发放卡券失败!");
                throw new BizException(StringUtils.isNotEmpty(errStr) ? errStr : "垫资方发放卡券失败！");
            }
            JSONObject respJson = JSONObject.parseObject(result.getData());
            return respJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }
    }

}
